import { defaultShouldUpdate, pathJoinParams } from '@/utils';
import { useEffect, useState } from 'react';
import { useHistory } from 'react-router-dom';
import { useCall, useQueryValue } from '.';

function useSaveQuery(saveQuery, data, shouldUpdate = defaultShouldUpdate) {
  const key = typeof saveQuery === 'string' ? saveQuery : 'search';
  const queryValue = useQueryValue(key);
  const [state, setState] = useState(data);
  const history = useHistory();

  useEffect(() => {
    setState(data);
    if (!saveQuery) return;
    const { location } = history;
    if (shouldUpdate(state, data)) {
      history.replace(pathJoinParams(location.search, { [key]: data }));
    }
  }, [data]);

  useEffect(() => {
    if (!saveQuery) return;
    const queryData = JSON.parse(queryValue);
    if (shouldUpdate(state, queryData)) {
      setState(queryData);
    }
  }, [queryValue]);

  return state;
}

export function useSaveFormQuery(saveQuery, form, shouldUpdate = defaultShouldUpdate) {
  const [formData, setFormData] = useState();
  const queryData = useSaveQuery(saveQuery, formData, shouldUpdate);

  const update = useCall(() => {
    setFormData(form.getFieldsValue());
  });

  useEffect(() => {
    if (!saveQuery) return;
    if (shouldUpdate(formData, queryData)) {
      form.setFieldsValue(queryData);
      update();
    }
  }, [queryData]);

  return update;
}

export default useSaveQuery;
